package com.uetoken.cn.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.FeedBackImgAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.UploadFileBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.PhotoUtils;
import com.uetoken.cn.view.DialogHelper;
import com.yanzhenjie.durban.Durban;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 意见反馈
 */
public class FeedBackActivity extends BaseActivity implements WebResponse{

    @BindView(R.id.edt_activity_feed_back_content)
    EditText     mEdtContent;
    @BindView(R.id.ry_activity_feed_back_img)
    RecyclerView mRyImg;
    @BindView(R.id.tv_activity_feed_back_commit)
    TextView     mTvCommit;
    @BindView(R.id.iv_activity_feed_back_back)
    ImageView    mIvBack;
    @BindView(R.id.tv_activity_feed_back_title)
    TextView     mTvTitle;
    @BindView(R.id.tv_activity_feed_back_my)
    TextView     mTvMy;
    @BindView(R.id.edt_activity_feed_back_title)
    EditText mEdtTitle;
    /**
     * 意见反馈的图片Drawable集合
     */
    private List<Drawable> imgList = new ArrayList<>();
    /**
     * 上传图片成功后服务器返回的url地址集合
     */
    private List<String> urlList = new ArrayList<>();

    private FeedBackImgAdapter mAdapter;
    private PhotoUtils mPhotoUtils;

    /**
     * 裁剪图片Intent请求码
     */
    private static final int CROP_IMAGE_REQUEST_CODE     = 200;
    /**
     * 上传图片到服务器的网络请求码
      */
    private static final int NETWORK_REQUEST_UPLOAD_PHOTO = 10;
    /**
     * 提交意见反馈的网络请求码
     */
    private static final int NETWORK_REQUEST_COMMIT_FEED_BACK_INFO = 20;

    @Override
    public int getLayoutId() {
        return R.layout.activity_feed_back;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        /*状态栏沉浸式*/
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mTvTitle.setText(getResources().getString(R.string.str_feed_back));
        mRyImg.setLayoutManager(new GridLayoutManager(this,4));

    }

    @Override
    public void initData() {
        mPhotoUtils = new PhotoUtils();

        mPhotoUtils.setPhotoPathListener(new PhotoUtils.PhotoPathListener() {
            @Override
            public void getPathSuccess(String path) {
                //拍照成功后裁剪图片
                mPhotoUtils.cropImage(FeedBackActivity.this, path, 1, 1);
            }
        });

        imgList.add(ContextCompat.getDrawable(this,R.drawable.ic_feed_back));
        mAdapter = new FeedBackImgAdapter(R.layout.item_feed_back_imag,imgList);
        mRyImg.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {

                //最后一张图片的点击事件
                if (position== imgList.size()-1){
                    if (imgList.size()>5){
                        //最多只能上传5张图片(5张图片，1张默认的图片不算在5里面)
                        ToastUtils.showShort(getResources().getString(R.string.str_feed_back_imag_most_five));
                    }else{

                        //当前手机版本低于23时，用此方法来判断相机是否可用(主要是用户手动关闭权限)
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
                            if (!PhotoUtils.cameraIsCanUse()){
                                //相机不可用
                                ToastUtils.showShort(getResources().getString(R.string.str_camera_not_use));
                                return;
                            }
                        }

                        AndPermission.with(FeedBackActivity.this).runtime().permission(Permission.Group.CAMERA,Permission.Group.STORAGE).onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                DialogHelper.showCameraDialog(mPhotoUtils);
                            }
                        }).onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                ToastUtils.showShort(getResources().getString(R.string.str_camera_not_use));
                            }
                        }).start();
                    }

                }else{
                    new QMUIDialog.MessageDialogBuilder(FeedBackActivity.this).setTitle(getResources().getString(R.string.str_delete_picture))
                            .setMessage(getResources().getString(R.string.str_weather_delete_current_picture)).addAction(getResources().getString(R.string.str_cancel), new QMUIDialogAction.ActionListener() {


                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }).addAction(getResources().getString(R.string.str_confirm), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            mAdapter.remove(position);
                        }
                    }).show();
                }

            }
        });
    }

    @Override
    public void init() {

    }

    @OnClick({R.id.iv_activity_feed_back_back,R.id.tv_activity_feed_back_my, R.id.tv_activity_feed_back_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_activity_feed_back_back:
                finish();
                break;
            case R.id.tv_activity_feed_back_my:
                startActivity(new Intent(this,FeedBackListActivity.class));
                break;
            case R.id.tv_activity_feed_back_commit:
                commitFeedBackInfo();
                break;
        }
    }

    /**
     * 提交意见反馈信息
     */
    private void commitFeedBackInfo() {
        //意见反馈标题
        String title = mEdtTitle.getText().toString();
        //意见反馈内容
        String content = mEdtContent.getText().toString();

        if (TextUtils.isEmpty(title)){
            ToastUtils.showShort(getResources().getString(R.string.str_feed_back_title_not_empty));
            return;
        }
        if (TextUtils.isEmpty(content)){
            ToastUtils.showShort(getResources().getString(R.string.str_feed_back_content_not_empty));
            return;
        }
        String url = "";
        if (urlList.size()!=0){
            //将所有的图片地址用stringBuffer拼接起来，用逗号分开
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < urlList.size(); i++) {
                stringBuffer.append(urlList.get(i)+",");
            }
            //图片url(去掉了末尾的逗号)
            url = stringBuffer.toString().substring(0,stringBuffer.toString().length()-1);
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this,ApiHelper.getCreateFeedBackUrl(),NETWORK_REQUEST_COMMIT_FEED_BACK_INFO,
                Params.getCreateFeedBackParams(title,content,url));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CROP_IMAGE_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> mImageList = Durban.parseResult(data);
                    if (!mImageList.isEmpty()) {
                      //始终保持默认图片在最后面(先移除掉加号，到后面再添加进来)
                       if (imgList.size()==1){
                           imgList.remove(0);
                       }else if (imgList.size()>1){
                           imgList.remove(imgList.size()-1);
                       }
                       String path = mImageList.get(0);
                        //裁剪图片成功后添加图片到集合
                       imgList.add(Drawable.createFromPath(path));
                       imgList.add(ContextCompat.getDrawable(this,R.drawable.ic_feed_back));
                       mAdapter.notifyDataSetChanged();
                       showLoading();
                       OkHttpUtils.getInstance().getStringWithParam(FeedBackActivity.this, ApiHelper.getUploadFileUrl(),NETWORK_REQUEST_UPLOAD_PHOTO ,Params.getUploadFileUrlParams(PhotoUtils.imageToBase64(path), ImageUtils.getImageType(path).getValue()));
                    }
                }
                break;
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        dissmissDialog();
        switch (requestCode){
            case NETWORK_REQUEST_UPLOAD_PHOTO:
                UploadFileBean uploadFileBean = new Gson().fromJson(response, UploadFileBean.class);
                if (uploadFileBean.getResult()>0){
                    urlList.add(uploadFileBean.getData().getFullurl());
                }else {
                    ToastUtils.showShort(uploadFileBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_COMMIT_FEED_BACK_INFO:
                JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
                String message = obj.get("message").getAsString();
                int result = obj.get("result").getAsInt();
                if (result>0){
                    ToastUtils.showShort(message);
                    mEdtTitle.setText("");
                    mEdtContent.setText("");
                    urlList.clear();
                    imgList.clear();
                    //提交后只保留默认的图片
                    imgList.add(ContextCompat.getDrawable(this,R.drawable.ic_feed_back));
                    mAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showShort(message);
                }

                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }
}
